package com.oocl.zero.datahandle.action.impl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.oocl.zero.datahandle.action.AppAction;
import com.oocl.zero.datahandle.service.CustomerService;
import com.oocl.zero.datahandle.service.impl.CustomerServiceImpl;

public class TCPAppAction implements AppAction {

	private ServerSocket server;
	private Socket accept;
	private CustomerService appService=new CustomerServiceImpl(); 
	
	public TCPAppAction(int port){
		super();
		try {
			this.server = new ServerSocket(port);
		} catch (IOException e) {
			this.server = null;
		}
	}
	public void service(InputStream in, OutputStream out) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		BufferedWriter writer =  new BufferedWriter(new OutputStreamWriter(out));
		
		String content=null;
		String str;
		
		str="command input format: L|C xml|line id|birth";
		writer.write(str);
		writer.newLine();
		
		str="input:";
		writer.write(str);
		writer.flush();
		while((content=reader.readLine())!=null){
			
			String[] ss = content.split("\\s+");
			if(isValidate(ss)){
				StringBuilder buf=new StringBuilder();
				for (String s : ss) {
					buf.append(s);
					buf.append("#");
				}
				content=buf.toString();
				appService.handle(content,out);
			}else{
				str="input err";
				writer.write(str);
				writer.newLine();
			}
		}
	}

	
	private boolean isValidate(String[] ss) {
		boolean isValidate=true;
		String[] regex=new String[3];
		regex[0] = "L|C";
		regex[1] = "xml|line";
		regex[2] = "id|birth";
		
		Pattern p;
		Matcher m ;
		
		if(ss!=null && ss.length==3){
			for(int i=0;i<ss.length;i++){
				p=Pattern.compile(regex[i]);
				m=p.matcher(ss[i]);
				isValidate &= m.matches();
			}
		}
		return isValidate;
	}

	public void start() {
		//
		if(server==null){
			throw new NullPointerException("server start fail:server is null");
		}
		//
		try {
			accept = server.accept();
			InputStream in = accept.getInputStream();
			OutputStream out = accept.getOutputStream();
			
			service(in,out);
			
		} catch (IOException e) {
//			log
//			e.printStackTrace();
		}
	}

	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		destroy();
	}

	private void destroy() throws IOException {
		if(accept!=null){
			accept.close();
		}
		if(server!=null){
			server.close();
		}
	}
}
